package cn.interceptor;

import cn.entity.Users;
import cn.util.JWTUtil;
import cn.util.ServerResponse;
import cn.util.UsersLoginAnno;
import com.alibaba.fastjson.JSON;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

//拦截器，拦截请求
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       response.setContentType("application/json;charset=UTF-8");
       if(!(handler instanceof HandlerMethod)){
           return true;
       }
        HandlerMethod handlerMethod=(HandlerMethod)handler;
       //得到目标方法
        Method method=handlerMethod.getMethod();
        //判断有没有注解
        if(method.isAnnotationPresent(UsersLoginAnno.class)){
            //获取值
            UsersLoginAnno annotation = method.getAnnotation(UsersLoginAnno.class);
            if(annotation.value()){
                ServerResponse result=null;
                //需要进行验证
                //获取token
                String headerToken=request.getHeader("Authorization");
                if(headerToken==null){
                    result=new ServerResponse("1","无token,请先登录");
                    response.getWriter().write(JSON.toJSONString(result));
                    return false;
                }else{
                    try {
                        headerToken=JWTUtil.updateToken(headerToken);
                    }catch(Exception ex){
                        result=new ServerResponse("1","token验证出现异常");
                        response.getWriter().write(JSON.toJSONString(result));
                        return false;
                    }
                    if(result==null){
                        response.setHeader("token",headerToken);
                        return true;
                    }
                }
            }
        }
        return true;
    }
}
